<?php

namespace control;
/*
*账套类
*/

class companyClass extends adIndexClass
{
    private const page  = 'company';
    private const table = 'company';
    private const title = '账套';
    public static array $accountingRule;
    public const codeLength = '4-3-2-2';//科目编码默认长度

    public function __construct()
    {
        parent::__construct();
        self::$accountingRule = ['smallEnterpriseRule' => L('finance.table.smallEnterpriseRule'), 'enterpriseRule' => L('finance.table.enterpriseRule')];
    }


    /**
     * 返回会计准则名称或键
     * @param int $nameOrKey 1：返回键/0:返回名字
     * @return string
     */
    public static function returnRule($nameOrKey = 0): string
    {
        $company = query('company', "coid = '" . self::$coid . "'");
        if (empty($company['coid'])) {
            return L('finance.table.wzdzt');
        }
        return $nameOrKey === 0 ? self::$accountingRule[$company['rule']] : $company['rule'];
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'name'      => [
                        'name'  => "名称",
                        'width' => 200,
                    ],
                    'rule'      => [
                        'name'  => '会计准则',
                        'width' => 200,
                    ],
                    'startDate' => [
                        'name'  => '启用时间',
                        'width' => 120,
                        'sort'  => 1,
                    ],
                    'taxType'   => [
                        'name'  => '纳税性质',
                        'width' => 200,
                    ],
                    'unit'      => [
                        'name'  => '单位',
                        'width' => 70,
                    ],
                    'auditText' => [
                        'name'  => '凭证审核',
                        'width' => 200,
                    ],
                    'range'     => [
                        'name'  => '查看范围',
                        'width' => 200,
                    ],
                    'managerId' => [
                        'name'  => '记账人',
                        'width' => 150,
                    ],
                    'time'      => [
                        'name'  => '创建时间',
                        'width' => 150,
                        'sort'  => 1,
                    ]
                ];
        }
        return $tr;
    }
    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('finance.table.ztmc') => text(array("name" => "name")),
                    '会计准则'                  => select(["name" => "rule", 'title' => '会计准则', 'option' => self::$accountingRule]),
                    '纳税性质'                  => select(["name" => "taxType", 'title' => '纳税性质', 'option' => para('taxType', '，')]),
                ],
                [
                    '纳税人名称' => text(array("name" => "invoiceCompany")),
                ],
            ]
        ], 1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url    = root . "control/adIndex.html?cla=" . self::page;
//        if ($this->power(self::page, "edit")) {
//            $button .= "<span onclick=\"newIframe('账套详情','" . $url . "&fun=edit')\" class='spanButton'>" . L('finance.table.add') . "</span>\n ";
//        }
//        if ($this->power(self::page, "del")) {
//            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('finance.table.shan_chu') . "</span>\n";
//        }
//        if ($this->power(self::page, "delAll")) {
//            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'delAll'})\">" . L('finance.table.emptyStr') . "</span>\n";
//        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

//    public function homeSearch()
//    {
//        //like查询数组
//        $like = array(
//            "name" => $this->post('name'),//标签
//        );
//        //全等查询数组
//        $equal = array();
//        //排序
//        $orderBy = $this->listSort(array(
//            "search" => $this->post('list_sort_key') ?: 'time',
//            "sort"   => $this->post('list_sort') ?: "desc",
//            "array"  => array(),
//        ));
//        //获取查询结果
//        $where = search(array("like" => $like, "=" => $equal));
//        $page  = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
//        //获取自定义字段参数
//        $installSearch = $this->installSearch();
//        $body          = [];
//        //表格控件区
//        $liButton = array(
//            $this->checkAll("listForm", "listId")
//        );
//        $url      = root . "control/adIndex.html?cla=" . self::page;
//        foreach ($page['array'] as $array) {
//            //列表控件
//            $dominate      = array(
//                "box"  => array("name" => "listId", "value" => $array['coid']),
//                "edit" => array("title" => '编辑', "click" => "newIframe('账套详情','" . $url . "&fun=edit&id=" . $array['coid'] . "')"),
//                "detail" => array("title" => '详情', "click" => "newIframe('账套详情','" . $url . "&fun=detail&id=" . $array['coid'] . "')"),
//            );
//            $array['rule'] = self::$accountingRule[$array['rule']];
//            $liButton[]    = $this->dominate($dominate);
//            //本行初始化
//            $row = [];
//            foreach ($installSearch['key'] as $key) {
//                switch ($key) {
//                    case 'name':
//                        $sign = '';
//                        if ($array['coid'] == self::$coid) {
//                            $sign = $this->nowCoid();
//                        }
//                        $row[] = "<span class='hands-url' onclick=\"changeCoid('{$array['coid']}')\">{$array['name']}</span>" . $sign;
//                        break;
//                    case 'auditText':
//                        $auditText = $array['isAudit'] ? L('finance.table.xu_yao_shen_he') : L('finance.table.bxysh');
//                        $row[]     = $auditText;
//                        break;
//                    case 'range':
//                        $range = componentClass::showSelector($array['selector']);
//                        $range = $range ?: L('finance.table.quan_bu');
//                        $row[] = $range;
//                        break;
//                    case 'managerId':
//                        $row[] = self::findStaff($array['managerId']);
//                        break;
//                    default:
//                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
//                }
//            }
//            $body[] = $row;
//        }
//
//        //控件
//        $button = "";
//        //生成页面
//        $li = $this->li(array(
//            "body"        => $body,
//            "install"     => $installSearch,
//            "button"      => array("html" => $liButton),
//            "orderBySign" => $orderBy,
//            "page"        => $page['para'],
//        ));
//        //返回
//        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . $this->style() . $this->js() . "</form>" . clear . $page['button'] . clear;
//        return json_encode($json, 320);
//    }

    public function nowCoid()
    {
        return <<<eof
<span class="active-coid">当前账套</span>
eof;

    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        $delPower   = $this->power(self::page, "del");
        $editPower  = $this->power(self::page, "edit");
        $clearPower = $this->power(self::page, "delAll");
        //like查询数组
        $like = array(
            "name"           => $this->post('name'),
            "invoiceCompany" => $this->post('invoiceCompany'),
        );
        //全等查询数组
        $equal = array(
            "taxType" => $this->post('taxType'),
            "rule"    => $this->post('rule'),
        );

        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal));
        $page  = $this->page(array("table" => self::table, "where" => $where, "order" => "time asc"));
        //获取表头
        //获取记录
        $html          = "<ul class='tag-list-ul'>";
        $root          = root;
        $idColloection = $this->staffCombination(true);
        $roleColloection = implode(',',json_decode(self::$user['role'],true));
        $url           = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            $style = '';
            if ($array['coid'] == self::$coid) {
                $style = "display:block";
            }
//            $box = <<<eof
//<label class="listCheckbox"><input name="listId[]" type="checkbox" value="{$array['coid']}"><span></span></label>
//eof;
            $editButton = '';
            if (self::$coid != $array['coid'] &&
                (self::total(['table' => self::table, 'where' => " coid = '$array[coid]' and (selector is null or (concat(',',replace(selector,';',','),',') regexp concat(',',replace('$idColloection',',',',|,'),','))>0)"]) > 0
                && self::total(['table'=>self::table, 'where' => " coid = '$array[coid]' and (roleSelector is null or (concat(',',replace(roleSelector,';',','),',') regexp concat(',',replace('$roleColloection',',',',|,'),','))>0)"]) > 0)) {
                $editButton .= <<<efo
<img alt="切换为此账套" title="切换为此账套" onclick="changeCoid('{$array['coid']}')" src="{$root}img/control/switch_coid.svg">
efo;
            }
            if ($editPower) {
                $editButton .= <<<efo
<img alt="编辑账套" title="编辑账套"  onclick="newIframe('账套详情','{$url}&fun=edit&id={$array['coid']}')" src="{$root}img/control/edit.svg">
efo;
            }
            $editButton.=<<<eof
<img alt="账套详情" title="账套详情"  onclick="newIframe('账套详情','{$url}&fun=detail&id={$array['coid']}')" src="{$root}img/control/detail.svg">
eof;

            if ($clearPower) {
                $editButton .= <<<efo
<img alt="清空账套" title="清空账套"  onclick="layer('{$this->get('cla')}', 'operate', {'act': 'delAll',id:'{$array['coid']}'})" src="{$root}img/control/clear.svg">
efo;
            }
            if ($array['isDel'] && $delPower) {
                $editButton .= <<<efo
<img alt="删除账套" title="删除账套"  onclick="layer('company','operate',{act:'del',id:'{$array['coid']}'})" src="{$root}img/control/delete.svg">
efo;
            }
            $array['rule'] = self::$accountingRule[$array['rule']];
            $url           = root . "control/adIndex.html?cla=" . self::page;
            $html          .= <<<efo
<li>
     <div class="tag-contain">
           <div class="tag-contain-title">
                 <div class="tag-contain-title-text">{$array['name']}</div>
                 <div class="tag-contain-title-edit">
                  $editButton
                 </div>
           </div>
           <div class="tag-contain-body">
                 <ul class="tag-contain-ul">
                     <li>会计准则：{$array['rule']}</li>
                     <li>纳税性质：{$array['taxType']}</li>
                     <li>建账时间：{$array['startDate']}</li>
                 </ul>
           </div>
           <div class="used-ico" style="{$style}">当前账套</div>
     </div>
</li>
efo;
        }


        if ($this->power(self::page, "edit")) {

            $html .= <<<eof
<li>
     <div class="tag-contain tag-contain-add" title="新增账套" onclick="newIframe('账套详情','{$url}&fun=edit')">
     <div class="tag-contain-add-sign">+</div>
     <div class="tag-contain-add-title">新增账套</div>
     </div>
</li>
eof;
        }
        $html .= <<<efo
</ul>
efo;
        $html .= $this->style() . $this->js();


        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $html . "</form>" . clear . $page['button'] . clear;
        return json_encode($json, 320);
    }

    private function js(): string
    {
        return <<<eof
<script>
$("[name='listForm'] .tableMany tr").on('dblclick',function(e) {
   changeCoid($(this).find("[name='listId[]']").val());
})
function addRow(){
     $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=roleEdit',$("form[name='mxForm']").serialize(),function(res) {
         if (res.warn === 2){
            $(".edit-block-ul").append(res.html);
       }else{
           msg(res.warn,'error');
       }
    },'json');
}
</script>
eof;
    }

    /**
     * 样式
     */
    private function style(): string
    {
        return <<<eof
<style>

.tag-contain-title{border-bottom: 1px solid #d7d7d7;padding: 10px;display: flex}
.tag-contain .used-ico{display: none;position: absolute;width: 108px;height: 25px;background-color: #598CE6;color: white;line-height:25px;text-align: center;right: -24px;bottom:16px;transform: rotate(-45deg)}
.tag-list-ul{}
.tag-list-ul>li{float: left;margin: 10px 10px 0 0}
.tag-contain{width: 400px;height: 175px;border: 1px solid #d7d7d7;border-radius: 2px;position: relative;overflow: hidden}
.tag-contain-title-text{font-weight: bold;font-size: 14px;flex: 1}
.tag-contain-title-box{width: 30px}
.tag-contain-title-edit>img{width: 22px;height: 22px;cursor: pointer;margin-left: 5px}
.tag-contain-body{padding: 10px;overflow: auto}
.tag-contain-ul li{margin: 5px 0}
.tag-edit-content{text-align: right}
.tag-edit-content img:nth-child(2){width: 20px;cursor: pointer}
.tag-edit-content img:nth-child(1){width: 22px;cursor: pointer}
.label-edit-ul li{float: left}
.add-attr-button{border: 2px solid #6aacfb;margin-top: 5px;color: #6aacfb;font-weight: bold;font-size: 21px; width: 16px;height: 16px;text-align: center;line-height: 13px;cursor: pointer;border-radius: 2px;}
.active-coid{border: 1px solid #6aacfb;padding: 0 3px;color: #6aacfb;margin-left: 10px;border-radius: 3px;font-size: 12px}
.comapny-name:hover{text-decoration: underline;color: #6aacfb;cursor: pointer}
.tag-contain-add{text-align: center;color: #e6e6e6;display: flex;flex-direction: column;justify-content: center;cursor: pointer;border-style: dashed}
.tag-contain-add .tag-contain-add-sign{font-weight: bold;font-size: 60px;height: 45px}
.tag-contain-add .tag-contain-add-title{font-size: 30px;}
.tag-list-ul{width: 100%;height: calc(100vh - 138px);overflow: auto;}
</style>
eof;

    }


    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id       = $this->get('id') ?: suiji();
        $info     = query(self::table, " coid = '" . $id . "' ");
        $readOnly = $info['coid'] ? 'disabled' : '';
        $ico      = query('file', "targetId = '$info[coid]' and target = '公司LOGO'");
        $photo    = array(
            array("title" => '公司LOGO', 'type' => '公司LOGO', "url" => $ico['src'] ?? '', "fileId" => $ico['id'] ?? '', "id" => $info['coid']),
        );
        //表单
        $data['html']   = $this->pageEdit([
            "table"  => [
                '基本信息' => [
                    [
                        must . L('finance.table.ztmc') . "："           => text(["name" => "name", "value" => $info['name']]),
                        must . L('finance.table.ztqyny') . "："         => text(["name" => "startDate", 'laydate' => ['type' => 'month'], "value" => $info['startDate']]),
                        must . L('finance.table.hui_ji_zhun_ze') . "：" => select(["name" => "rule", 'title' => L('finance.table.qing_xuan_ze'), 'class' => 'width200', 'other' => $readOnly, 'option' => self::$accountingRule, "value" => $info['rule']]) . componentClass::tipComponent(L('finance.table.hjzzschjbnqh')),
                        must . L('finance.table.zzszl') . "：" => radio(["name" => "taxType", "value" => para('taxType', '，'), 'checked' => $info['taxType']]),
                    ],
                    [
                        must . L('finance.table.pzsh') . "："  => radio(["name" => "isAudit", "value" => [1 => L('finance.table.xu_yao_shen_he'), 0 => L('finance.table.bxysh')], 'checked' => $info['isAudit'] ?: 0]),
                        "负责会计" . "："                          => selectMultiple(["name" => "managerId", 'where' => "state != '离职' and workFlow = '已复核'", 'table' => 'staff', 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => '请选择', "value" => $info['managerId']]),
                        L('finance.table.taxName') . "：" => text(["name" => "invoiceCompany", "value" => $info['invoiceCompany']]),
                        L('finance.table.taxNum') . "："  => text(["name" => "invoiceNo", "value" => $info['invoiceNo']]),
                    ],

                    [
                        L('finance.table.address') . "：" => text(["name" => "addressAndTel", "value" => $info['addressAndTel']]),
                        L('finance.table.bank') . "：" => text(["name" => "bankName", "value" => $info['bankName']]),
                    ],
                    [
                        "查看(部门|职位|员工)：" => componentClass::staffSelector($info['selector']),
                    ],
                    [
                        "查看(角色)：" => self::showUl($info['roleSelector'],false) . "<span class='spanButton' onclick=\"layer('" . self::page . "','role',$('form[name=companyEditForm]').serialize())\">选择</span>"
                    ],
                ],
                '图案管理' => [
                    [
                        fileUploadClass::singleFrameImgUpload(['array' => $photo, 'formName' => 'companyEditForm', 'power' => self::page]),
                    ],
                ]
            ],
            'hidden' => hidden(['name' => 'id', 'value' => $info['coid'] ?: $id]),
        ]);
        $button[]       = [
            "name"  => '保存',
            "type"  => "点击事件",
            "cla"   => $this->get('cla'),
            "fun"   => "subForm('" . self::page . "EditForm', root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
            "post"  => ["id" => $this->get('id')],
            'style' => 'li-btn-blue-bg',
        ];
        $data['button'] = $this->tableShowButton($button);
        //返回
        return $this->tab($data) . $this->js();
    }

    public function editEdit()
    {
        //附件
        $fileIdArr    = $this->post('iconId');
        $id           = $this->post('id') ?: self::getId();
        $where        = " coid = '$id' ";
        $info         = query(self::table, $where);
        $field        = [
            "name"           => $this->post('name'),
            "startDate"      => $this->post('startDate'),
            "rule"           => $this->post('rule') ?: $info['rule'],
            "taxType"        => $this->post('taxType'),
            "isAudit"        => $this->post('isAudit'),
            "invoiceCompany" => $this->post('invoiceCompany'),
            "invoiceNo"      => $this->post('invoiceNo'),
            "addressAndTel"  => $this->post('addressAndTel'),
            "bankName"       => $this->post('bankName'),
            'selector'       => $this->post('staff')[0] ?? '',//员工选择器
            'auditStid'      => $this->post('auditStid'),
            'managerId'      => $this->post('managerId'),
            'cashierId'      => $this->post('cashierId'),
            'unit'           => $this->post('unit'),
            'roleSelector'   => $this->post('roleId') ? implode(';', $this->post('roleId')) : ''
        ];
        $staff        = componentClass::returnStaffId($field['selector']);
        $field['see'] = implode(',', $staff);
        $annotation   = [
            'name'      => L('finance.table.ztmc'),
            'startDate' => L('finance.table.ztqyny'),
            'rule'      => L('finance.table.hui_ji_zhun_ze'),
            'taxType'   => L('finance.table.zzszl'),
            'isAudit'   => L('finance.table.pzsh'),
        ];
        $rules        = [
            'name'      => 'required',
            'startDate' => 'required',
            'rule'      => 'required',
            'taxType'   => 'required',
            'isAudit'   => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('finance.table.company_edit_permission');
        } elseif (static::total(array('table' => self::table, 'where' => "name = '$field[name]' and coid !='$id'")) > 0) {
            $json['warn'] = L('finance.table.yczcmc');
        } elseif (!empty($info['id']) && $info['rule'] != $field['rule']) {
            $json['warn'] = L('finance.table.hjzzbnqh');
        } else {
            $this->startTrans();
            if (!$info['coid']) {
                $field        = array_merge($field, [
                    'coid' => $id,
                    'stid' => $this->control['stid'],
                    'time' => $this->time,
                    'codeLength'=>self::codeLength
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            //添加主表ID到附件表
            if (is_array($fileIdArr)) {
                $warn = update(array(
                    'table' => 'file',
                    'field' => ['targetId' => $id],
                    'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"
                ));
                if ($warn != '更新成功') {
                    $json['warn'] = $warn;
                }
            }
            if (in_array($json['warn'], ['新增成功', '更新成功'])) {
                $this->commitTrans();
                //添加日志
                $text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $field['name'], $id], L('finance.table.company_edit_text'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     */
    public function role()
    {
        $layerId = $this->get('cla') . ucwords($this->get('fun'));
        $html    =
            text(["name" => "name", "title" => "角色名称"]) .
            hidden(array('name' => 'roleIds', 'value' => $this->post('roleId') ? implode(',', $this->post('roleId')) : ''));
        $button  = "<input onclick=\"addRow();$('#" . $layerId . "').remove()\"  type='button' class='button m-l-5' value='提交'>";
        $html    =
            $this->search($html, cla: self::page, fun: 'roleSearch')
            ;
        return $this->layer(["title" => '添加', "height" => 600, "width" => 1100, "remove" => 1, "html" => $html, "button" => $button]);
    }


    /**
     *添加产品
     */
    public function roleSearch()
    {
        $roleIdArr = $this->post('roleIds') ? explode(',', $this->post('roleIds')) : [];
        $where     = " 1=1 and id not in ('" . implode("','", $roleIdArr) . "')";
        $like      = [
            'name' => $this->post('name'),
        ];
        $equal     = [
        ];
        $where     .= search(["like" => $like, "=" => $equal]);
        $page      = $this->page([
            "table" => "role",
            "where" => $where,
            "order" => "list asc",
        ]);
        //获取表头
        $checkAll = $this->checkAll("mxForm", "mxId");
        $tr[]     = [$checkAll, '角色名称', '权限', '排序号'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "mxId", "value" => $array['id']),
            );
            $checkBox = $this->dominate($dominate);
            $power    = "";
            $powerNow = json_decode($array['power'], true);
            foreach ($this->powerAll as $oneArray) {
                foreach ($oneArray as $twoArray) {
                    foreach ($twoArray as $threeArray) {
                        foreach ($threeArray as $menuTwoName => $menuTwoValue) {
                            if (isset($powerNow[$menuTwoName]) && count(array_intersect(array_keys($menuTwoValue), (array)$powerNow[$menuTwoName])) > 0) {
                                $power .= $menuTwoValue['name'] . "；";
                            }
                        }
                    }
                }
            }
            $tr[] = array(
                $checkBox,
                $array['name'],
                zishu($power, 30),
                $array['list'],
            );
        }
        $json['html'] = $page['hint'] .
            "<form name='mxForm'>" .
            $this->tableMany(array("tr" => $tr)) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function roleEdit()
    {
        $mxIdArr = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择角色';
        } else {
            $li = '';
            foreach ($mxIdArr as $mxId) {
                $role      = query('role', "id = '$mxId'");
                $delButton = '<div class="delete-button" onclick="del_li(this)"></div>' . hidden(array('name' => 'roleId[]', 'value' => $role['id']));
                if (!empty($role['id'])) {
                    $li .= '<div class="li-item"><div class="li-item-data">' . $role['name'] . '</div>' . $delButton . '</div>';
                }
            }
            $json['html'] = $li;
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " coid = '{$this->get('id')}'");
        if (empty($info['coid'])) {
            $html = L('feeApply.detail.empty');
        } else {
            //菜单
            $data = array(
                "id"    => $info['coid'],
                "title" => $info['name'],
            );

            $button = [];
            if ($this->power(self::page, "edit")) {
                //按钮
                $button[] = [
                    "name"  => L('feeApply.detail.edit'),
                    "type"  => "顶部页卡",
                    "title" => L('feeApply.detail.editDetail'),
                    "url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['coid'],
                ];

            }
            if ($this->power(self::page, "del") && $info['isDel']) {
                //按钮
                $button[] = [
                    "name" => L('feeApply.detail.del'),
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'del', "id" => $info['coid']],
                ];
            }
            $ico   = query('file', "targetId = '$info[coid]' and target = '公司LOGO'");
            $photo = array(
                array("title" => '公司LOGO', "url" => $ico['src'] ?? '', 'type' => '公司LOGO', "fileId" => $ico['id'] ?? ''),
            );
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html']   = $this->tableShow(array(
                '账套信息' => array(
                    array(
                        '账套名称'   => $info['name'],
                        '账套启用年月' => $info['startDate'],
                        '会计准则'   => self::$accountingRule[$info['rule']],
                        "增值税种类" => $info['taxType'],
                    ),
//                    array(
//                       '记账人' => self::findStaff($info['managerId']),
//                       '审核人' => self::findStaff($info['auditStid']),
//                       '出纳人' => self::findStaff($info['cashierId']),
//                    ),
                    array(
                        "凭证审核"  => $info['isAudit'] ? L('finance.table.xu_yao_shen_he') : L('finance.table.bxysh'),
                        '纳税人名称'  => $info['invoiceCompany'],
                        '纳税人识别号' => $info['invoiceNo'],
                        '地址、电话'  => $info['addressAndTel'],
                    ),
                    array(
                        '开户行及账号' => $info['bankName'],
//                        '单位' => $info['unit'],
                        '查看(部门|职位|员工)' => componentClass::showSelector($info['selector']),
                        '查看(角色)' => self::showUl($info['roleSelector']),
                        '账套ID' => $info['coid'],
                    ),
                ),
                '图案管理' => array(
                    array(
                        fileUploadClass::singleFrameImgUpload(['array' => $photo, 'formName' => 'companyEditForm', 'power' => self::page]),
                    )
                ),

            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    // 操作中转
    public function operate()
    {
        $act  = $this->post('act') ?? '';
        $pwd  = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            case 'delAll':
                $act      = 'del';
                $msg      = L('finance.table.company_del_title');
                $title    = self::page . 'DeleteAll';
                $function = 'deleteAll';
                $form     = self::page . 'OperateForm, listForm';
                $power    = '';
                $pwd      = true;
                break;
            default:
                $act      = 'del';
                $msg      = L('finance.table.company_del_title');
                $title    = self::page . 'Delete';
                $function = 'delete';
                $form     = self::page . 'OperateForm, listForm';
                $power    = '';
                $pwd      = true;
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'word'     => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('finance.table.nmzscdzx');
        } elseif (empty($array)) {
            $json['warn'] = L('finance.table.nygsjdmzxzn');
        } elseif (isset($_POST['password']) && verifyPwd($this->post('password'), self::$user['password']) === false) {
            $json['warn'] = '密码错误';
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " coid = '$id' ");
                if (!$info['isDel']) {
                    //返回
                    $warn = L('finance.table.company_del_failed');
                } else {
                    $this->deleteTable($id, true);
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " coid = '$id' "));
                    delete(array("table" => 'option_setting', "where" => " coid = '$id' "));
                    //删除科目
                    delete(array("table" => 'subject', "where" => " coid = '$id' "));
                    //返回
                    $warn = L('finance.table.sccg');
                    $x++;
                }

                $text .= str_replace(['{{name}}', '{{id}}'], [$info['name'], $info['coid']], L('finance.table.company_del_text')) . $warn . "。<br>";
            }

            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('finance.table.company_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('finance.table.company_del_msg'));
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function deleteAll()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "delAll")) {
            $json['warn'] = L('finance.table.nmzqkdzx');
        } elseif (empty($array)) {
            $json['warn'] = L('finance.table.nygsjdmzxzn');
        } elseif (isset($_POST['password']) && verifyPwd($this->post('password'), self::$user['password']) === false) {
            $json['warn'] = '密码错误';
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " coid = '$id' ");
                $this->deleteTable($id);
                //返回
                $warn = L('finance.table.emptySuccess');
                $x++;
                $text .= str_replace(['{{name}}', '{{id}}'], [$info['name'], $info['coid']], L('finance.table.company_del_text')) . $warn . "。<br>";
            }
            static::rSet('loginPage', 1);
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('finance.table.company_empty_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('finance.table.company_empty_msg'));
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 清空此coid的表
     */
    private function deleteTable($coid, $isAll = false)
    {
        global $conf;
        $sql = "SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_SCHEMA ='{$conf['databaseName']}' and TABLE_TYPE = 'BASE TABLE'";
        $all = self::sqlFind($sql);
        foreach ($all as $array) {
            $sql    = "SELECT COLUMN_NAME FROM information_schema.columns WHERE TABLE_SCHEMA='{$conf['databaseName']}' AND TABLE_NAME='{$array['TABLE_NAME']}'";
            $result = self::sqlFind($sql);
            $field  = [];
            foreach ($result as $val) {
                $field[] = $val['COLUMN_NAME'];
            }
            $whiteField = [];
            if (!$isAll) {
                $whiteField = ['business_voucher_template', 'business_voucher_template_detail', 'warehouse_type', 'option_setting', 'warehouse_position', 'tag', 'tag_detail', 'routing', 'routing', 'routing', 'routing', 'routing_detail', 'company', 'bom', 'process',
                    'team', 'team_detail', 'bom', 'bom', 'bom_detail',
                    'quarantine', 'quarantine_item', 'quarantine_reason', 'mold', 'equipment', 'supplier', 'product_line', 'kehu', 'warehouse', 'account', 'material', 'material_type',
                    'subject', 'subject', 'subject_assist', 'currency', 'voucher_word', 'account', 'cash', 'subject_demo', 'cash_demo', 'voucher_word_demo', 'asset_debt_demo', 'asset_debt_formula_demo', 'period_end_setting_demo',
                    'period_end_setting_detail_demo', 'profit_income_demo', 'profit_income_formula_demo'];
            }
            if (in_array('coid', $field, true) && !in_array($array['TABLE_NAME'], $whiteField)) {
                if (in_array($array['TABLE_NAME'], ['sale_order', 'sale_send_order', 'sale_refund_order', 'purchase_order', 'voucher', 'purchase_refund_order', 'purchase_get_order'])) {
                    //删除文件
                    $result = find(array('table' => 'file', 'where' => " targetId in (select id from {$array['TABLE_NAME']} where coid = '$coid')"));
                    foreach ($result['array'] as $val) {
                        fileDelete($val['src']);
                        delete(array('table' => 'file', 'where' => " id = '$val[id]'"));
                    }
                }
                sqlExec("DELETE FROM `{$array['TABLE_NAME']}` WHERE coid = '$coid'");
            }
        }
    }

    /**
     * 仅保留基础数据
     */
    private function deleteAllData()
    {
        global $conf;
        $sql = "SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_SCHEMA ='{$conf['databaseName']}' and TABLE_TYPE = 'BASE TABLE'";
        $all = self::sqlFind($sql);
        foreach ($all as $array) {
            $sql    = "SELECT COLUMN_NAME FROM information_schema.columns WHERE TABLE_SCHEMA='{$conf['databaseName']}' AND TABLE_NAME='{$array['TABLE_NAME']}'";
            $result = self::sqlFind($sql);
            $field  = [];
            foreach ($result as $val) {
                $field[] = $val['COLUMN_NAME'];
            }
            $whiteField = ['business_voucher_template', 'business_voucher_template_detail', 'warehouse_type', 'option_setting', 'warehouse_position', 'tag', 'tag_detail', 'routing', 'routing', 'routing', 'routing', 'routing_detail', 'company', 'bom', 'process',
                'team', 'team_detail', 'bom', 'bom', 'bom_detail',
                'quarantine', 'quarantine_item', 'quarantine_reason', 'supplier', 'product_line', 'kehu', 'warehouse', 'account',
                'material', 'material_type',
                'subject', 'subject', 'subject_assist', 'currency', 'voucher_word', 'account', 'cash', 'subject_demo', 'cash_demo', 'voucher_word_demo', 'asset_debt_demo', 'asset_debt_formula_demo', 'period_end_setting_demo',
                'period_end_setting_detail_demo', 'profit_income_demo', 'profit_income_formula_demo'];
            if (in_array('coid', $field, true) && !in_array($array['TABLE_NAME'], $whiteField)) {
                if (in_array($array['TABLE_NAME'], ['sale_order', 'sale_send_order', 'sale_refund_order', 'purchase_order', 'voucher', 'purchase_refund_order', 'purchase_get_order'])) {
                    //删除文件
                    $result = find(array('table' => 'file', 'where' => " targetId in (select id from {$array['TABLE_NAME']})"));
                    foreach ($result['array'] as $val) {
                        fileDelete($val['src']);
                        delete(array('table' => 'file', 'where' => " id = '$val[id]'"));
                    }
                }
                sqlExec("DELETE FROM `{$array['TABLE_NAME']}` WHERE 1");
            } elseif (!in_array('coid', $field, true)) {
                $whiteField = ['staff', 'user', 'para', 'img', 'department', 'role', 'job', 'talent_pool', 'examine', 'log',
                    'print_template', 'subject_demo', 'cash_demo', 'voucher_word_demo', 'asset_debt_demo', 'asset_debt_formula_demo', 'period_end_setting_demo',
                    'period_end_setting_detail_demo', 'profit_income_demo', 'company', 'profit_income_formula_demo'];
                if (!in_array($array['TABLE_NAME'], $whiteField)) {
                    if (in_array($array['TABLE_NAME'], ['file', 'account_elect_file'])) {
                        //删除文件
                        $result = find(array('table' => $array['TABLE_NAME']));
                        foreach ($result['array'] as $val) {
                            fileDelete($val['src']);
                        }
                    }
                    sqlExec("DELETE FROM `{$array['TABLE_NAME']}` WHERE 1");
                }
            }
        }
    }

    /**
     * @param $value
     * @param bool $isShow
     * @return string
     */
    public static function showUl($value, $isShow = true): string
    {
        $li = '';
        if (!is_array($value)) {
            $value = explode(';', $value);
        }
        $editClass = $isShow ? '' : 'edit-block-ul';
        foreach ($value as $v) {
            $role      = query('role', "id = '$v'");
            $delButton = '<div class="delete-button" onclick="del_li(this)"></div>' . hidden(array('name' => 'roleId[]', 'value' => $role['id']));
            if (!empty($role['id'])) {
                if ($isShow) {
                    $delButton = '';
                }
                $li .= '<div class="li-item"><div class="li-item-data">' . $role['name'] . '</div>' . $delButton . '</div>';
            }
        }
        return <<<eof
<div class="show-block-ul $editClass">
    $li
</div>
eof;
    }

    /**
     * 获取设置
     * @param $key
     * @return mixed|string
     */
    public static function getSetting($key){
        $company = query('company',"coid = '".self::$coid."'");
        $setting = $company['setting']?json_decode($company['setting'],true):[];
        return $setting[$key] ?? '';
    }
}

